import config from "./Config.js";
import cache from "../cache/index.js";
// import { aiSay } from "../../wenyanyixin/index.js";
const name = config.name;

const getRoomList = async (msg, bot) => {
  let roomList;
  if (cache.has("roomList")) {
    roomList = cache.get("roomList");
  } else {
    roomList = await bot.Room.findAll();
    cache.set("roomList", roomList);
    // console.log("roomList群聊联系:", roomList);
  }
  return roomList;
};
/**获取到我加入的群聊列表 */
const getGroup = async (msg, bot) => {
  // 存储群聊名称
  let groupNames = [];
  let roomList;
  // 获取所有的群聊
  if (cache.has("roomList")) {
    roomList = cache.get("roomList");
  } else {
    roomList = await bot.Room.findAll();
    // cache.set("roomList", roomList);
    // console.log("roomList群聊联系:", roomList);
  }
  for (const contact of roomList) {
    // 只处理群聊
    const topicName = await contact.topic();
    groupNames.push(topicName);
  }
  // console.log("Groups the robot has joined:");
  // console.log(groupNames);
  return groupNames;
};
/**加群 */
export const isAddRoom = async (msg, bot) => {
  // 关键字 加群 处理
  if (msg.text() == "加群") {
    const roomList = await getGroup(msg, bot);
    let roomListName = roomList;
    let info = `${name}当前管理群聊有${roomListName.length}个，回复群聊名即可加入哦\n\n`;
    roomListName.map((v) => {
      info += "【" + v + "】" + "\n";
    });
    msg.say(info);
    return true;
  }
  return false;
};
/**回复信息是所管理的群聊名 */
export const isRoomName = async (msg, bot) => {
  // console.log("加群验证!!!");
  const roomList = await getRoomList(msg, bot);
  // console.log(roomList, msg.text());

  let inRoomFlag = false;
  let roomId;
  // console.log("开始校验");
  for (const contact of roomList) {
    // 只处理群聊
    const topicName = await contact.topic();
    // console.log(contact.id, topicName, msg.text(), topicName == msg.text());
    if (topicName == msg.text()) {
      inRoomFlag = true;
      roomId = contact.id;
      break;
    }
  }
  // console.log(inRoomFlag, "inRoomFlag");
  if (inRoomFlag) {
    // 通过群聊id获取到该群聊实例
    const room = await bot.Room.find({ id: roomId });

    // // 获取当前room信息
    // // 判断是否在房间中 在-提示并结束
    if (await room.has(msg.from())) {
      await msg.say("您已经在房间中了");
      return true;
    }
    // // 发送群邀请
    await room.add(msg.from());
    await msg.say("已发送群邀请");
    return true;
  }
  return false;
};
/**回复群聊信息 处理函数 */
export const roomMessageReply = () => {};

/**只对初心发的使用ai */
export const isChuxing = (msg, bot) => {
  console.log(msg.talker().name());
  if (msg.talker().name() == "以往") {
    // aiSay(msg);
    return true;
  } else {
    return false;
  }
};
